﻿/********************************************************
 *  ██████╗  ██████╗████████╗██╗
 * ██╔════╝ ██╔════╝╚══██╔══╝██║
 * ██║  ███╗██║        ██║   ██║
 * ██║   ██║██║        ██║   ██║
 * ╚██████╔╝╚██████╗   ██║   ███████╗
 *  ╚═════╝  ╚═════╝   ╚═╝   ╚══════╝
 * Geophysical Computational Tools & Library (GCTL)
 *
 * Copyright (c) 2023  Yi Zhang (yizhang-geo@zju.edu.cn)
 *
 * GCTL is distributed under a dual licensing scheme. You can redistribute 
 * it and/or modify it under the terms of the GNU Lesser General Public 
 * License as published by the Free Software Foundation, either version 2 
 * of the License, or (at your option) any later version. You should have 
 * received a copy of the GNU Lesser General Public License along with this 
 * program. If not, see <http://www.gnu.org/licenses/>.
 * 
 * If the terms and conditions of the LGPL v.2. would prevent you from using 
 * the GCTL, please consider the option to obtain a commercial license for a 
 * fee. These licenses are offered by the GCTL's original author. As a rule, 
 * licenses are provided "as-is", unlimited in time for a one time fee. Please 
 * send corresponding requests to: yizhang-geo@zju.edu.cn. Please do not forget 
 * to include some description of your company and the realm of its activities. 
 * Also add information on how to contact you by electronic and paper mail.
 ******************************************************/

#include "meshdata_tensor.h"

gctl::meshdata_tensor::meshdata_tensor(std::string in_name, mesh_data_type_e in_type, 
	int d_size, bool if_output, gctl::tensor init_val) : meshdata::meshdata(in_name, in_type, if_output)
{
	if (d_size <= 0)
	{
		std::string err_str = "mesh data's size is smaller than zero. From meshdata_tensor::meshdata_tensor(...)";
		throw runtime_error(err_str);
	}

	valtype = Tensor;
	datval.resize(d_size, init_val);

	//std::clog << "A new meshdata_tensor object is created." << std::endl;
}

gctl::meshdata_tensor::~meshdata_tensor()
{
	datval.clear();

	//std::clog << "A meshdata_tensor object is destroyed." << std::endl;
}

void *gctl::meshdata_tensor::get_datval()
{
	return &datval;
}

void gctl::meshdata_tensor::load_binary(std::ifstream &infile)
{
	// 读入数据
	for (int i = 0; i < datval.size(); i++)
	{
		infile.read((char*)&datval[i], sizeof(gctl::tensor));
	}
	return;
}

void gctl::meshdata_tensor::save_binary(std::ofstream &outfile)
{
	// 我们首先输出数据类型，赋值类型与数据长度 这三个值都是整形变量
	// 我们在读入二进制文件时会在函数外先读入这三个值以新建数据对象
	outfile.write((char*)&dattype, sizeof(int));
	outfile.write((char*)&valtype, sizeof(int));
	// 输出数据对象的名称
	int name_size = datname.size();
	outfile.write((char*)&name_size, sizeof(int));
	outfile.write((char*)datname.c_str(), name_size);
	// 输出数据
	for (int i = 0; i < datval.size(); i++)
	{
		outfile.write((char*)&datval[i], sizeof(gctl::tensor));
	}
	return;
}